{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img src=\".\\\\Logo.png\" alt=\"some_text\">\n",
    "<h1> 第二讲 程序设计基础</h1>\n",
    "<a id=backup></a>\n",
    "<H2>目录</H2>  \n",
    "\n",
    "[2.1 程序执行过程](#Section1)  \n",
    "[2.2 程序实例](#Section2)  \n",
    "[2.3 程序的基本结构](#Section3)     \n",
    "[2.4 顺序结构](#Section4)  \n",
    "[2.5 分支结构](#Section5)  \n",
    "[2.6 循环结构](#Section6) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section1> </a>\n",
    "## 2.1 程序执行过程\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt\n",
    "x = np.linspace(0,100*np.pi)\n",
    "plt.plot(x,np.sin(10*x+np.pi/2),x,np.cos(x))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 程序设计语言：机器语言、汇编语言、高级语言\n",
    "## 编译和解释\n",
    "编译：fortran C C++ C#\n",
    "解释：basic JavaScript PHP \n",
    "Python？？？\n",
    "Python语言执行的几种方式：\n",
    "\n",
    "分析程序执行过程-IPO：  \n",
    "a. Input模块：  \n",
    "b. Process模块：  \n",
    "c. Output模块：  \n",
    "\n",
    "\n",
    "\n",
    "[返回](#backup)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = Section2> </a>\n",
    "## 2.2 程序实例\n",
    "\n",
    "<p><a href=\"https://yanghailin.blog.csdn.net/article/details/81126087?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-5.no_search_link\">\n",
    "this is example of python</a></p"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Created on Thu Jul 19 19:51:08 2018\n",
    "有四个数字：1、2、3、4，能组成多少个互不相同且无重复数字的三位数？各是多少？\n",
    "@author: yhl\n",
    "\"\"\"\n",
    " \n",
    "L=[]\n",
    "a=[1,2,3,4]\n",
    " \n",
    "#for i in range(len(a)):\n",
    " \n",
    "for val_1 in a:   #   for(i=1;i<n;I++)\n",
    "    for val_2 in a:\n",
    "        for val_3 in a:\n",
    "            if(val_1 == val_2 or val_1 == val_3 or val_2 == val_3):\n",
    "                continue;\n",
    "            else:\n",
    "                L.append(str(val_1)+str(val_2)+str(val_3))\n",
    " \n",
    " \n",
    "print(len(L)) \n",
    "print (L)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n=0\n",
    "for i in range(1,5):\n",
    "    for j in range(1,5):\n",
    "        for k in range(1,5):\n",
    "            if( i != k ) and (i != j) and (j != k):\n",
    "                n=n+1\n",
    "                print (i,j,k,\"n=\",n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "企业发放的奖金根据利润提成。\n",
    "利润(I)低于或等于10万元时，奖金可提10%；\n",
    "利润高于10万元，低于20万元时，低于10万元的部分\n",
    "按10%提成，高于10万元的部分，可提成7.5%；\n",
    "20万到40万之间时，高于20万元的部分，可提成5%；\n",
    "40万到60万之间时高于40万元的部分，可提成3%；\n",
    "60万到100万之间时，高于60万元的部分，可提成1.5%;\n",
    "高于100万元时,超过100万元的部分按1%提成。\n",
    "从键盘输入当月利润I，求应发放奖金总数？\n",
    "'''\n",
    " \n",
    "profit = 0\n",
    "I = int(input(\"please input: \"))\n",
    "if(I<=10):\n",
    "    profit = 0.1 * I\n",
    "elif(I <= 20):\n",
    "    profit = 10 *0.1 + (I - 10)*0.075\n",
    "elif(I <=40):\n",
    "    profit = 10 * 0.1 + (20 - 10)*0.075 + (I - 20)*0.05\n",
    "elif(I <= 60):\n",
    "    profit = 10 * 0.1 + (20 - 10)*0.075 + (40 - 20)*0.05 + (I - 40)*0.03\n",
    "elif(I <= 100):\n",
    "    profit = 10 * 0.1 + (20 - 10)*0.075 + (40 - 20)*0.05 + (60 - 40)*0.03 + (I - 60)*0.015\n",
    "else : \n",
    "    profit = 10 * 0.1 + (20 - 10)*0.075 + (40 - 20)*0.05 + (60 - 40)*0.03 + (100 - 60)*0.015 + (I -100)*0.01\n",
    "    \n",
    "print (\"profit=\",profit)\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "i = int(input('净利润:'))\n",
    "arr = [1000000,600000,400000,200000,100000,0]\n",
    "rat = [0.01,0.015,0.03,0.05,0.075,0.1]\n",
    "r = 0\n",
    "for idx in range(0,6):\n",
    "    if i>arr[idx]:\n",
    "        r+=(i-arr[idx])*rat[idx]#r=r+nnn\n",
    "        print((i-arr[idx])*rat[idx])\n",
    "        i=arr[idx]\n",
    "print (\"profit=\",r)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python 数字类型转换\n",
    "有时候，我们需要对数据内置的类型进行转换，数据类型的转换，你只需要将数据类型作为函数名即可。\n",
    "\n",
    "int(x) 将x转换为一个整数。\n",
    "\n",
    "float(x) 将x转换到一个浮点数。\n",
    "\n",
    "complex(x) 将x转换到一个复数，实数部分为 x，虚数部分为 0。\n",
    "\n",
    "complex(x, y) 将 x 和 y 转换到一个复数，实数部分为 x，虚数部分为 y。x 和 y 是数字表达式。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=Section3></a>\n",
    "## 2.3程序的基本结构\n",
    "结构化程序的三大基本结构：\n",
    "\n",
    "a.顺序结构  \n",
    "b.分支结构  \n",
    "c.循环结构  \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "[返回](#backup)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=Section4></a>\n",
    "## 2.4顺序结构\n",
    "\n",
    "### 数学函数\n",
    "<table><tr>\n",
    "<th>函数</th><th>返回值 ( 描述 )</th></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-abs.html\" rel=\"noopener noreferrer\">abs(x)</a></td><td>返回数字的绝对值，如abs(-10) 返回 10</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-ceil.html\" rel=\"noopener noreferrer\">ceil(x) </a></td><td>返回数字的上入整数，如math.ceil(4.1) 返回 5</td></tr>\n",
    "<tr><td><p>cmp(x, y)</p></td>\n",
    "<td>如果 x &lt; y 返回 -1, 如果 x == y 返回 0, 如果 x &gt; y 返回 1。 <strong style=\"color:red\">Python 3 已废弃，使用 (x&gt;y)-(x&lt;y) 替换</strong>。 </td>\n",
    "</tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-exp.html\" rel=\"noopener noreferrer\">exp(x) </a></td><td>返回e的x次幂(e<sup>x</sup>),如math.exp(1) 返回2.718281828459045</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-fabs.html\" rel=\"noopener noreferrer\">fabs(x)</a></td><td>返回数字的绝对值，如math.fabs(-10) 返回10.0</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-floor.html\" rel=\"noopener noreferrer\">floor(x) </a></td><td>返回数字的下舍整数，如math.floor(4.9)返回 4</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-log.html\" rel=\"noopener noreferrer\">log(x) </a></td><td>如math.log(math.e)返回1.0,math.log(100,10)返回2.0</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-log10.html\" rel=\"noopener noreferrer\">log10(x) </a></td><td>返回以10为基数的x的对数，如math.log10(100)返回 2.0</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-max.html\" rel=\"noopener noreferrer\">max(x1, x2,...) </a></td><td>返回给定参数的最大值，参数可以为序列。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-min.html\" rel=\"noopener noreferrer\">min(x1, x2,...) </a></td><td>返回给定参数的最小值，参数可以为序列。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-modf.html\" rel=\"noopener noreferrer\">modf(x) </a></td><td>返回x的整数部分与小数部分，两部分的数值符号与x相同，整数部分以浮点型表示。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-pow.html\" rel=\"noopener noreferrer\">pow(x, y)</a></td><td> x**y 运算后的值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-round.html\" rel=\"noopener noreferrer\">round(x [,n])</a></td><td><p>返回浮点数 x 的四舍五入值，如给出 n 值，则代表舍入到小数点后的位数。</p>\n",
    "<p><strong>其实准确的说是保留值将保留到离上一位更近的一端。</strong></p>\n",
    "</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-sqrt.html\" rel=\"noopener noreferrer\">sqrt(x) </a></td><td>返回数字x的平方根。</td></tr>\n",
    "</table>\n",
    "\n",
    "### 随机数函数\n",
    "随机数可以用于数学，游戏，安全等领域中，还经常被嵌入到算法中，用以提高算法效率，并提高程序的安全性。\n",
    "\n",
    "Python包含以下常用随机数函数：\n",
    "\n",
    "<table><tr>\n",
    "<th>函数</th><th>描述</th></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-choice.html\" rel=\"noopener noreferrer\">choice(seq)</a></td><td>从序列的元素中随机挑选一个元素，比如random.choice(range(10))，从0到9中随机挑选一个整数。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-randrange.html\" rel=\"noopener noreferrer\">randrange ([start,] stop [,step]) </a></td><td>从指定范围内，按指定基数递增的集合中获取一个随机数，基数默认值为 1</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-random.html\" rel=\"noopener noreferrer\">random() </a></td><td> 随机生成下一个实数，它在[0,1)范围内。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-seed.html\" rel=\"noopener noreferrer\">seed([x]) </a></td><td>改变随机数生成器的种子seed。如果你不了解其原理，你不必特别去设定seed，Python会帮你选择seed。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-shuffle.html\" rel=\"noopener noreferrer\">shuffle(lst) </a></td><td>将序列的所有元素随机排序</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-uniform.html\" rel=\"noopener noreferrer\">uniform(x, y)</a></td><td>随机生成下一个实数，它在[x,y]范围内。</td></tr>\n",
    "</table>\n",
    "\n",
    "### 三角函数\n",
    "Python包括以下三角函数：\n",
    "<table><tr>\n",
    "<th>函数</th><th>描述</th></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-acos.html\" rel=\"noopener noreferrer\">acos(x)</a></td><td>返回x的反余弦弧度值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-asin.html\" rel=\"noopener noreferrer\">asin(x)</a></td><td>返回x的反正弦弧度值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-atan.html\" rel=\"noopener noreferrer\">atan(x)</a></td><td>返回x的反正切弧度值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-atan2.html\" rel=\"noopener noreferrer\">atan2(y, x)</a></td><td>返回给定的 X 及 Y 坐标值的反正切值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-cos.html\" rel=\"noopener noreferrer\">cos(x)</a></td><td>返回x的弧度的余弦值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-hypot.html\" rel=\"noopener noreferrer\">hypot(x, y)</a></td><td>返回欧几里德范数 sqrt(x*x + y*y)。 </td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-sin.html\" rel=\"noopener noreferrer\">sin(x)</a></td><td>返回的x弧度的正弦值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-tan.html\" rel=\"noopener noreferrer\">tan(x)</a></td><td>返回x弧度的正切值。</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-degrees.html\" rel=\"noopener noreferrer\">degrees(x)</a></td><td>将弧度转换为角度,如degrees(math.pi/2) ，  返回90.0</td></tr>\n",
    "<tr><td><a target=\"_blank\" href=\"/python3/python3-func-number-radians.html\" rel=\"noopener noreferrer\">radians(x)</a></td><td>将角度转换为弧度</td></tr>\n",
    "</table>\n",
    "\n",
    "### 数学常量\n",
    "\n",
    "<table><tr>\n",
    "<th>常量</th><th>描述</th></tr>\n",
    "<tr><td>pi</td><td>数学常量 pi（圆周率，一般以π来表示）</td></tr>\n",
    "<tr><td>e</td><td>数学常量 e，e即自然常数（自然常数）。</td></tr>\n",
    "</table>\n",
    "\n",
    "[返回](#backup)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 安装Graphviz\n",
    "- 1.下载https://www.graphviz.org/download/   \n",
    "- 2.安装  \n",
    "- 3.设定环境变量path，增加C:\\Program Files\\windows_10_msbuild_Release_graphviz-7.0.1-win32\\Graphviz\\bin   \n",
    "**也可在安装时候选择增加graphviz的路径到系统path中**\n",
    "- 4.pip install graphviz  \n",
    "- 5.import graphviz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install graphviz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import graphviz\n",
    "dot=graphviz.Digraph(comment='the round table',name=\"顺序结构\",node_attr={'shape': 'box'})\n",
    "dot.node('1','Start')\n",
    "dot.node('2','input Radius =?',shape='parallelogram')\n",
    "dot.node('3','Print Radius')\n",
    "dot.node('4','Caculating Area')\n",
    "dot.node('5','Caculating perimeter')\n",
    "dot.node('6','print')\n",
    "dot.node('7','end')\n",
    "dot.edges(['12','23','34','45','56','67'])\n",
    "dot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "''' \n",
    "计算圆周长\n",
    "'''\n",
    "Radius = eval(input(\"请输入圆半径:\"))\n",
    "print(\"Ridus=\",Radius)\n",
    "Area = 3.1415*Radius*Radius\n",
    "perimeter  = 2*3.1415*Radius \n",
    "print(\"面积和周长:\",Area,perimeter)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=section4></a>\n",
    "## 2.5分支结构\n",
    "### 2.5.1 Python比较运算符\n",
    "\n",
    "以下假设变量a为10，变量b为20：\n",
    "<table><tr>\n",
    "<th width=\"10%\">运算符</th><th>描述</th><th>实例</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>==</td><td> 等于 - 比较对象是否相等</td><td> (a == b) 返回 False。 </td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>!=</td><td> 不等于 - 比较两个对象是否不相等</td><td> (a != b) 返回 True。 </td>\n",
    "</tr>\n",
    "\n",
    "<tr>\n",
    "<td>&gt;</td><td> 大于 - 返回x是否大于y</td><td> (a &gt; b) 返回 False。</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>&lt;</td><td> 小于 - 返回x是否小于y。所有比较运算符返回1表示真，返回0表示假。这分别与特殊的变量True和False等价。注意，这些变量名的大写。</td><td> (a &lt; b) 返回 True。 </td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>&gt;=</td><td> 大于等于 - 返回x是否大于等于y。</td><td> (a &gt;= b) 返回 False。</td>\n",
    "\n",
    "</tr>\n",
    "<tr>\n",
    "<td>&lt;=</td><td> 小于等于 - 返回x是否小于等于y。</td><td> (a &lt;= b) 返回 True。 </td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "### 2.5.2 Python逻辑运算符        \n",
    "Python语言支持逻辑运算符，以下假设变量 a 为 10, b为 20:\n",
    "<table><tr>\n",
    "<th>运算符</th><th>逻辑表达式</th><th>描述</th><th>实例</th>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>and</td><td>x and y</td><td> 布尔\"与\" - 如果 x 为 False，x and y 返回 x 的值，否则返回 y 的计算值。  </td><td> (a and b) 返回 20。</td>\n",
    "</tr>\n",
    "<tr>\n",
    "<td>or</td><td>x or y</td><td>布尔\"或\" - 如果 x 是 True，它返回 x 的值，否则它返回 y 的计算值。</td><td> (a or b) 返回 10。</td>\n",
    "</tr>\n",
    "<tr><td>not</td><td>not x</td><td>布尔\"非\" - 如果 x 为 True，返回 False 。如果 x 为 False，它返回 True。</td><td> not(a and b) 返回 False </td>\n",
    "</tr>\n",
    "</table>\n",
    "\n",
    "[返回](#backup)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.3 条件控制语句\n",
    "Python 条件语句是通过一条或多条语句的执行结果（True 或者 False）来决定执行的代码块。\n",
    "\n",
    "可以通过下图来简单了解条件语句的执行过程:\n",
    "\n",
    "<img src=\".//img//if-condition.jpg\" width=\"250\"></img>\n",
    "\n",
    "<img src=\".//img//python-if.webp\" width=\"150\"></img>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 例题 求绝对值。\n",
    "\n",
    "输入：x\n",
    "$$\n",
    "\\begin{align}\n",
    "&&\\left|y\\right |= \\left\\{\\begin{matrix}\n",
    "x & if \\: x\\geq 0\\\\-x& if \\:x< 0\n",
    "\\end{matrix}\\right.{\\color{Red} }\n",
    "\\end{align}\n",
    "$$\n",
    "输出：y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dot=graphviz.Digraph(comment='the round table',name=\"分支结构\",node_attr={'shape': 'box'})\n",
    "dot.node('1','开始')\n",
    "dot.node('2','输入Real Number =?',shape='parallelogram')\n",
    "dot.node('3','判断RealNumber是否大于0？',shape='diamond')\n",
    "dot.node('4','RealNumber=RealNumber')\n",
    "dot.node('5','RealNumber=-RealNumber')\n",
    "dot.node('6','输出绝对值',shape='parallelogram')\n",
    "dot.node('7','结束')\n",
    "dot.edges(['12','23','34','35','46','56','67'])\n",
    "dot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "求绝对值。\n",
    "'''\n",
    "RealNumber = eval(input(\"输入实数:\"))\n",
    "\n",
    "if (RealNumber < 0):\n",
    "    RealNumber = -RealNumber\n",
    "print(\"绝对值:\",RealNumber)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=section6></a>\n",
    "## 2.6循环结构\n",
    "\n",
    "循环结构：\n",
    "\n",
    "while语句\n",
    "\n",
    "for语句\n",
    "\n",
    "循环分类：  \n",
    "当型循环  \n",
    "直到型循环  \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "[返回](#backup)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "char1 =\"a\"\n",
    "char2=\"b\"\n",
    "char3=\"c\"\n",
    "char=char1+char2+char3\n",
    "boor1=(char[2]==char3)\n",
    "print(boor1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 例题 整数累加：  \n",
    "输入：正整数R    \n",
    "处理：  \n",
    "S=1+2+3+…+R  \n",
    "<img src=\"./img/int_add.png\" width=\"150\">  \n",
    "输出：输出S"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "R = eval(input(\"请输入正整数:\"))\n",
    "i, S = 0, 0\n",
    "#i 循环变量\n",
    "#S 累加器初值最好定为0\n",
    "#注意初值设定\n",
    "while (i<=R):\n",
    "    print('S=',S,'i=',i)\n",
    "    S = S + i\n",
    "    i = i + 1\n",
    "    print('S=',S,'i=',i)\n",
    "print(\"累加求和\",S)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S= 1 i= 2\n",
      "S= 2 i= 3\n",
      "S= 6 i= 4\n",
      "S= 24 i= 5\n",
      "S= 120 i= 6\n",
      "累加求和 120\n"
     ]
    }
   ],
   "source": [
    "#累乘器\n",
    "R = eval(input(\"请输入正整数:\"))\n",
    "i, S = 1, 1\n",
    "#i 循环变量初值也不能为0，如果参与累乘\n",
    "#S 累乘器初值必须不为0\n",
    "#注意初值设定\n",
    "while(i<=R):\n",
    "   S=S*i\n",
    "   i+=1\n",
    "   print('S=',S,'i=',i)\n",
    "print(\"累加求和\",S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "例题 输入一个数n，求解$\\sum _{k=1}^n {k!} $"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "T= 1 j= 1\n",
      "S= 1 i= 1\n",
      "T= 2 j= 2\n",
      "S= 3 i= 2\n",
      "T= 6 j= 3\n",
      "S= 9 i= 3\n",
      "T= 24 j= 4\n",
      "S= 33 i= 4\n",
      "T= 120 j= 5\n",
      "S= 153 i= 5\n",
      "累加求和 153\n"
     ]
    }
   ],
   "source": [
    "#累加器+累乘器\n",
    "N = eval(input(\"请输入正整数:\"))\n",
    "i,j, S,T = 1,1, 0,1\n",
    "#i 循环变量初值也不能为0，如果参与累乘\n",
    "#S 累加器 \n",
    "#T 累乘器初值必须不为0\n",
    "#注意初值设定\n",
    "while(i<=N):\n",
    "   #j,T=1,1\n",
    "   #while(j<=i):\n",
    "   T=T*j #存储了上一次的k！的结果，(k+1)!=k!*(k+1) =>T*=j\n",
    "   j+=1\n",
    "\n",
    "   print(\"T=\",T,'j=',j-1)\n",
    "   S=S+T\n",
    "   i+=1\n",
    "   print('S=',S,'i=',i-1)\n",
    "print(\"累加求和\",S)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python 提供了 for 循环和 while 循环（在 Python 中没有 do..while 循环）:\n",
    "\n",
    "<table><tr><th style=\"width:30%\">循环类型</th><th>描述</th></tr>\n",
    "<tr><td><a href=\"/python/python-while-loop.html\" title=\"Python WHILE 循环\">while 循环</a></td><td>在给定的判断条件为 true 时执行循环体，否则退出循环体。</td></tr>\n",
    "<tr><td><a href=\"/python/python-for-loop.html\" title=\" Python FOR 循环\">for 循环</a></td><td>重复执行语句</td></tr>\n",
    "<tr><td><a href=\"/python/python-nested-loops.html\" title=\"Python 循环全套\">嵌套循环</a></td><td>你可以在while循环体中嵌套for循环</td></tr>\n",
    "</table>\n",
    "\n",
    "### 循环控制语句\n",
    "循环控制语句可以更改语句执行的顺序。Python支持以下循环控制语句：\n",
    "<table><tr><th style=\"width:30%\">控制语句</th><th>描述</th></tr>\n",
    "<tr><td><a href=\"/python/python-break-statement.html\" title=\"Python break 语句\">break 语句</a></td><td>在语句块执行过程中终止循环，并且跳出整个循环</td></tr>\n",
    "<tr><td><a href=\"/python/python-continue-statement.html\" title=\"Python  语句\">continue 语句</a></td><td>在语句块执行过程中终止当前循环，跳出该次循环，执行下一次循环。</td></tr>\n",
    "<tr><td><a href=\"/python/python-pass-statement.html\" title=\"Python pass 语句\">pass 语句</a></td><td>pass是空语句，是为了保持程序结构的完整性。</td></tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 例题 绘制数字图画\n",
    "   <img src=\".//img//jqm1.jpg\" width=\"150 \" alt=\"机器猫\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "UCCCCCCCCCCCCJJJJUYXzn|)1{}{}{{)/jxnnnnnuuuunnnuunnnnuunnnnxxxxxxxxxxrrrrrrjjjjjjjfffffffffffffffffttttftttt//\n",
      "L000000QQQQLLCCCCJUx/|(()()1{{}}}1|jxvvvvvvvvvvvvvuuuuuuunxnxxxrrrrrjjjffftttttttt///\\\\\\\\\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\//\n",
      "trvUJCCCUf/\\||((((|\\\\\\\\\\\\\\|||||||\\/trnuvvvvuuunnnnnxrrrrjjjfftt//\\/\\\\||||(()))))111111{{{{{{{{{}}{}}}}}}{{{{{{\n",
      "\\/\\\\/\\///////ttt///ttffjjjjjrxxnuuvuvvvvuuunnxxrrjfftt///\\\\||||(()))11{{{{}}}[[[[[]]]?????????????????????????\n",
      "xxnxxxxxxxnxxnnnnnnnnnnnuuuuuvvvvvvvvunnxxxrrjft//\\|(()111{{{{}}}[[[]]]]???----_____++++~~~~~~~~~~~~~~~~~+~+~+\n",
      "cXXXzzzzcccccvvvvvvvvuvvvvvvvvuuvunnxrr_!_?_~>,^`\"\"(1{}[[]]]]]?????-----__++++++++++~~~~~~~~~~~<<<<<<<<<<<<<<<\n",
      "XYYYXzXzzzccccccccvvcvcvvvvvvuunnxxrjf]/xzXYcxf1_+>l^`',i---________________++++++++++++++++~~~~~~~~<<<<~~~<~~\n",
      "jnuvvvvvcccccccccccvvvvvvvuuunxxrjfft\\}jvXYYYYUUUUJuv>!I:`.:i~+++_____---???]]]]]]]]]]]]]??-___!;,:i++_______-\n",
      "11{{1(/rnnuuvvvvvvvvvvvvunnxrrjfft\\||))1ucvvvvuunuuvczXntI:\"'.^i_?]]][}}}}{{{11)))((((())1`^,;ll;^ .\"][[[[[]]]\n",
      "))1{{{}}{1|jxxnuuuvvuvunnnxrfft/\\|))1{};fcunnxjf//\\\\tjnvzc[!I:`..<1)|\\\\///tt/tttttt///`<_--_+<!;' ^.|(||((()()\n",
      "\\\\\\()){}}[[]][1txuunnxxxjjff/\\\\((11{[[]--xunxrft/|)))(\\fxzXx{i!I^'':\\ttttttt//////\\;?{11[]+<!I`.iI^ ((||||\\||(\n",
      "|\\\\\\\\\\||(11{{}{1(\\tfjjfff//\\(()1{}[]]???--nurrjjt/\\())(\\txvXc\\<>il^'']\\///\\\\\\\\\\\\|,{|\\|){]+<!:''>l,.}1))((())))\n",
      "////ttfffffffjjrrrrjfft//|((11{}[[[][[[[[[}jzurjrrjf/\\\\/txvzUn|_~~i;`._)((())))(_\\///){]_<i:',~>I.)}}}{{{{1111\n",
      "jxrrjrrrxxnxxxxxxrjft/\\|()1{}}[[[}}}}{{1(\\\\/_czuxxnnnxrrxucXJLmr??_+i`'+{111{{{{fjjt\\)}?+>I'?_<l.[[[[[[[[[[[}}\n",
      "xuuuuuuuuuunnxrjjfft\\\\|)1{}}[[}{{{{{)|/tttttf/>uXzuxnczzzzXUCQOz|]{]_>'.]}}}}[{fnxrt\\1{-<,.]?+' ]]]]]]]]]]]]][\n",
      "nvvvvvvuuunnxxjff/\\|()1{{}}}{{111)|/tttftfft/\\|)1+YUUcuvUUJCL0ZwQ|}1{]I'{????I/xuvxt|1[-,i}[\".?????-------????\n",
      "vvcvvvvunnxrjft//|((){{{{{{111)|/ttftfftt/\\|()1{[]?-IfUUYXcc0Omqpft|(1<.]-?-_^|xuujt1}-`[?\" __________________\n",
      "uvvvvuuunxrjft\\\\|)){{{{{1)))(\\tffffff//\\|(1{{[]]--__+~<<IInYUYXJwYuuf)>'.'''``,!::^`^`.:''!<<~~++++++++++++++_\n",
      "uvvvunnxrjft/\\|()11{{11))(|/ffjjfjt/\\|(11{}]?--_++~~<>!I:^```zYYcx/){}]?-_++~><~>!l:\"`'..   ..i<<~~~~~~~~~~~~+\n",
      "uvvunnxrjt//\\(()1{{))))(|tfjrrjft/\\|)1{}[]---_+~<<i!I:,\"`'/ucvnrt\\){]-_+++~~_~<~>i!I;;;,\"`''....,!><<<<<<<<<~~\n",
      "uvunxxjft//|()111)1)((|/frrrjff/\\((1{}]??-_+~~<>il;:\"^^')uzzcnxt\\(){}[?-++<>ii><><<i>ilI;\"^^``'.  'ii>>>>>>>>>\n",
      "nuuxrjft/\\|()111))((|/tjrjjjt/\\|(1{}[]?__+~~<>!I::\"\"^``[xXXXzunxxnvChOvr|{?_<>i>>~<><>ilI,\"\"^\"\"I;..i!iiiiiiiii\n",
      "nnxrff//||(111))((|\\tjjrjft/\\|)11}[]?-_++~>>!I:,\"\"^^''.tcXYYXcvj&bbaBB$ &'f1?+<<<++_~<>i!:,\"`$B@[$\\.l!!!!!!!!!\n",
      "jrjft/\\|()111))((|/jjjjjf/\\|()1}}]?--_+~<>il;,\"\"\"^``''rvzXYYzvu@nnO$$$@%o%\\f1-___?[]]?_+<!:\"`b$@@X.  `;IllIlll\n",
      "/\\\\|())11{{1))((|tfjjjf/\\|(){{}[]--_+~<iilI::\"\"^``|\\vccvunrf/))}[]]__+~^ftUj(]?]{1))1}[?_<l\"``^^^^^\",^'..^;IIl\n",
      "<>!I,\"^^_?[{1))(\\ttftt/|()11[[]?__~~>>i!I;::,\"^`''juXXzcvuxft\\(){{]-+<~~?|YJu1]-+<!;,.J;,\",:!++~<<>>>>i:I',:;;\n",
      "-_~>lI,\"^^^~+]{|\\//\\|((1{}[]-_~>i!lII;;::::,,\"^```[xXUUYYXcvvxrft/\\|)}/1(|rp#Xzcuxf1]$$}[?a\\{)[}{})[{?+l`.I;;I\n",
      "]]-+<>!I:\"^`'^-}1{{}\"\"^^.l~~<<>>ii!lI;;,,\"\"\"^\"^^``'(<xYUJJJUUYXzcYzcvvuuuuuuxjt\\#dqZ0&r(}{)|//ffjft(-:`'llIlll\n",
      "{}[?-_~>!I:\"^^,;l!l!lI;,^`'''`;!iiii!lllI;;:,\"\"^^^``'.'`<1fcUCLQQQQLLLLLCCCCJUXvr/|){1(jXYXcvx)!^;llllIllllll!\n",
      "11{}[]-_~>il;,\",:l><<>ilI:,\"^``^;iiiiiilllII;:,\"\"^^^``''...rXZmpdpppqqwqqpwmwmZmZZZOO0QLCx/|`':;IIllllll!!!!!!\n",
      "11{}[[??-_~>>!lll+___++<>>i!I;,\"\"\"\",li!i!lII:::,\"^^^``'?fYCLQZQCLYYUzXYXucxuntxrjtr/|\\|})(}?_+'`:IIll!!!!!!!!!\n",
      "11{{}[]]-__+~~<<_?????--++~~<>>i!l;,,l!iii!lI;:,\"\"^\"|rcYJLLLCCCXzzvxufnjfft\\(\\t))|/(?]-}]?_-+i;^',Ill!!!!!!!ii\n",
      "11{{}}[[[]]????]????]???-_____+~<i!Ili>>>i!lI;::^_xcXUUJCCJJJCYYccuunxtt\\j\\/((//[}-1?[__?-]++-I,.';ll!!!!!iiii\n",
      ")())1111{{}}}[[]]]]??-_+~~~~~<>iii><<<<>>i:``^l|uvzYUUJJCLLUCCUUYcnjfrxffxfff((\\?{[1]--?-]}_-+>^`,^!l!!!iii>>>\n",
      ")((())11{{}[[]]??--_++__-----__+++++~~<<<<>l,tvzXYUUJCCCCJLUJUYXXzccnxrjrf///)/{{[|(?[[--{[}{}I,'Il!!!!iiii>>>\n",
      "((()))11{{{}}}[[]]]]]?????------____++++~<+/xvXYYXUJCCQOCCCCYYXccccucvunfftxt\\/1{/111\\{[t\\1{[-^^^Il!!iiiii>>>>\n",
      ")(())111{{}}}[[[[[]]]]??????----______++++rnzXvXcvrvXzCOZQOCQJYYzcuvcvuccruxtrjjjrj/t/||t\\\\?i\"`,l!!!!iiiii>>>>\n",
      "))))11{{{}}}}[[[[[]]]]???????----____++-?1vzXXXcuvnjjfrzU0mqw0LJCXzurjttjnXzcvcYuruvvx)1[_Il.ll!!!iiiiiiii>>>>\n",
      ")))111{{{}}}}}}[}[[]]]]]?]????-?---__++_)jcYJUYYzcunrxjxvzUOmqdkqQYvrt(1}})wm0CLQ0LXn/)]+i`.!iii>>>i>>>>>>><<<\n",
      "1)))1111{{{{{{{{{1{{1)1)1[{{}}]]]]?????_+~cJCLCCJYYzcccuczYLQmwdkbLXuj(1[]_+Cu{+(vQJc/)->:'~+_______________-?\n",
      "fttttt/|(f/|(f\\f\\f///f/t\\(((()){[[[}}{{{}{|nL0OOOO0LQCJJCLQQZwpddbwYur(1]_~\"!|\\\\\\(ZYzr|}i,.[[[[}}}{{{{1))((|(|\n",
      "vzujjffxx/\\|zjfrrrtt\\|((()))11{{11111)(\\/ttttjxCZmwwwmmmwqppddddpqwCcn/([?+<`]_--?-UYcr(?I;l,..?__---??]]]}{11\n",
      "vcUCvvuvcXvttrrx/tttttttffrrnucXYJCLQOZmqpdbha*O0QCJJXXUCOaaaaahhkhwLYnr/){-i`0O0OZZZm0Uvr\\j){<}){}[]]][]]]]]]\n",
      "C0ZZnrrrUZCUYXYUvXzXXYYJJJCQ0OZZZmwwqpdbbkkkhhhhhhhhhhhkkkkbbbdddpqqqqwqqqwmZ0QCCJYzcvunrt\\(1{}}}}}{{{{{{{{)1)\n",
      "UqmZO00OZqkLLCYXXYYZOZmmmmwwwwqqpqddbddddpppqpqqwwmmmZOZ0QQLCCUYYXXzzvunrrjff//\\\\|(()))11)))1))))))((|\\\\//tftr\n",
      "YLZwOOd0q0QC0CZQ0wqppdddddddddZmwZOL0ppqwmmmZO00QQLCJJUYXzcccvvvuuunnxxrrrxxrrjfftt/t///tt/tftfjncunrzLjunxXYU\n",
      "ZpkqdwkwOamwpwdpqqppdbkkkkkbbbbbhpqqqwwmZZOO0QLCCJJJJYYXXzzzzzzzzzzzccvvvuuuuuunnnxrrxxxnnuvccjbzCXdLLCCUYwUJZ\n",
      "wdpdpq0wwqppqppppwJ0m0pdhbhhkkkokbbdpqqwwmmZZZO000QQLLCJJJJUUUYYYYYYYXXzXzzXXXXYUYYXXYXYYYYUUJJQJJJYpZJUqQQpwm\n",
      "wwppqpCwwqpddpqqqqqwXb0ZdbhkhhkCkbbpdpppqqqwwwmZZZOO0000QQQLLLLLLCCCCCCCCCCCCCCCCLCCCCCCCCCLLQQ000OOZwwqpppwwZ\n",
      "OmmwdqvwppddddppqqmqZZYpbbkhhhhXkbkmmQddddppppppqqwwmmmZZZZZZZOOOOOOOOOOOOOOOOOOOOOOZZZZOZZZZq`W*'q;%&& k#bppq\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "<>:7: SyntaxWarning: invalid escape sequence '\\|'\n",
      "<>:7: SyntaxWarning: invalid escape sequence '\\|'\n",
      "C:\\Users\\H3C\\AppData\\Local\\Temp\\ipykernel_14456\\970160178.py:7: SyntaxWarning: invalid escape sequence '\\|'\n",
      "  \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \")\n"
     ]
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "show_heigth = 50\n",
    "show_width = 110\n",
    "#这两个数字是调出来的\n",
    "\n",
    "ascii_char = list(\n",
    "    \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \")\n",
    "#生成一个ascii字符列表\n",
    "char_len = len(ascii_char)\n",
    "\n",
    "pic = plt.imread(\"img//rabit.jpeg\")\n",
    "#使用plt.imread方法来读取图像，对于彩图，返回size = heigth*width*3的图像\n",
    "#matplotlib 中色彩排列是R G B\n",
    "#opencv的cv2中色彩排列是B G R\n",
    "\n",
    "pic_heigth, pic_width, _ = pic.shape\n",
    "#获取图像的高、宽\n",
    "\n",
    "gray = 0.2126 * pic[:, :, 0] + 0.7152 * pic[:, :, 1] + 0.0722 * pic[:, :, 2]\n",
    "#RGB转灰度图的公式 gray = 0.2126 * r + 0.7152 * g + 0.0722 * b\n",
    "\n",
    "#思路就是根据灰度值，映射到相应的ascii_char\n",
    "for i in range(show_heigth):\n",
    "    #根据比例映射到对应的像素\n",
    "    y = int(i * pic_heigth / show_heigth)\n",
    "    text = \"\"\n",
    "    for j in range(show_width):\n",
    "        x = int(j * pic_width / show_width)\n",
    "        text += ascii_char[int(gray[y][x] / 256 * char_len)]\n",
    "    print(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ! pip install -i http源\n",
    "新版ubuntu要求使用https源，要注意。\n",
    "\n",
    "清华：https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "\n",
    "阿里云：https://mirrors.aliyun.com/pypi/simple/\n",
    "\n",
    "中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/\n",
    "\n",
    "华中理工大学：https://pypi.hustunique.com/\n",
    "\n",
    "山东理工大学：https://pypi.sdutlinux.org/ \n",
    "\n",
    "豆瓣：https://pypi.douban.com/simple/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "%pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "li= !pip list\n",
    "for l in li:\n",
    "    if (\"numpy\" in l): \n",
    "        print(l)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
